package com.quanyan.ic.mq;

import com.alibaba.fastjson.JSON;
import com.alibaba.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import com.alibaba.rocketmq.common.message.MessageExt;
import com.quanyan.ic.cache.OrderMsgDao;
import com.quanyan.ic.cache.PlaceLightSettingDao;
import com.quanyan.ic.common.model.OrderMessage;
import com.quanyan.ic.constants.MQConstant;
import com.quanyan.ic.middleware.mq.rocketmq.consumer.AbstractMqConsumer;
import com.quanyan.ic.middleware.mq.rocketmq.consumer.MqConsumerStatus;
import com.quanyan.ic.middleware.mq.rocketmq.consumer.MqTopic;
import com.quanyan.ic.model.PlaceLightSetting;
import com.quanyan.ic.protocol.server.SendICMessageProcessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.SerializationUtils;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * MQ consumer，消费：
 * 场馆订单对应的场地智能灯自动控制消息
 */
@Component
public class PlaceOrderMessageConsumer extends AbstractMqConsumer {

    private static Logger logger = LoggerFactory.getLogger(PlaceOrderMessageConsumer.class);

    @Value("${rocketmq.nameServer}")
    private String nameServer;

    @Autowired
    private SendICMessageProcessor sendICMessageProcessor;
    @Autowired
    private PlaceLightSettingDao placeLightSettingDao;
    @Autowired
    private OrderMsgDao orderMsgDao;

    @PostConstruct
    public void start() {
        super.start();
        logger.info("PlaceOrderMessageConsumer started!");
    }

    @Override
    protected MqConsumerStatus process(List<MessageExt> messages, ConsumeConcurrentlyContext context) {
        try {
            logger.info("\n");
            logger.info("received MQ msg: {}", messages);
            if (messages.isEmpty()) {
                return MqConsumerStatus.CONSUMER_SUCCESS;
            }
            MessageExt messageExt = messages.get(0);
            String msgId = messageExt.getKeys();        //订单号
            byte[] bodyByte = messageExt.getBody();
            String j_orderMsg = new String(bodyByte);
            logger.info("orderMsg msgId={}, msg={}", msgId, j_orderMsg);
            OrderMessage orderMessage = null;
            try {
                orderMessage = JSON.parseObject(j_orderMsg, OrderMessage.class);
            } catch (Exception e) {
                e.printStackTrace();
                logger.warn("invalid json string, to deserialize ...");
                try {
                    orderMessage = (OrderMessage) SerializationUtils.deserialize(bodyByte);
                } catch (Exception e1) {
                    e1.printStackTrace();
                    logger.warn("deserialize error");
                    return MqConsumerStatus.CONSUMER_SUCCESS;
                }
            }
            if (orderMessage.getUseType() != null && orderMessage.getUseType() == 2) {
                logger.warn("ticket order, ignore");
                return MqConsumerStatus.CONSUMER_SUCCESS;
            }
            //消息格式验证
            if (!validateOrderMsg(orderMessage)) {
                logger.warn("orderMsg contains invalid field");
                return MqConsumerStatus.CONSUMER_SUCCESS;
            }
            PlaceLightSetting setting = placeLightSettingDao.getLightControlSetting(orderMessage.getPlaceId());
            if (setting == null) {
                //此场馆没有灯光设置
                logger.warn("place {} haven't the light control settings, ignore this mq msg", orderMessage.getPlaceId());
                return MqConsumerStatus.CONSUMER_SUCCESS;
            }

            //记录message到redis，用于错误分析，失败重试
            orderMsgDao.saveOrderMsg(orderMessage);

            //记录此订单对应的场地，在此订单时间段内的销售状态
            orderMsgDao.saveOrderTimeSegment(orderMessage);

            //根据场馆id下发到
            sendICMessageProcessor.sendICMessage(orderMessage);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("Msg convert error: {}", e.getMessage());
        }
        return MqConsumerStatus.CONSUMER_SUCCESS;
    }

    private boolean validateOrderMsg(OrderMessage orderMessage) {
        if (orderMessage.getOrderNo() == null || orderMessage.getPlaceId() == null
                || orderMessage.getSiteId() == null || orderMessage.getOrderStatus() == null) {
            return false;
        }
        return true;
    }

    @Override
    protected String getConsumerGroup() {
        return MQConstant.IC_LIGHT_CONTROL_CONSUMER_GROUP;
    }

    @Override
    protected String getNameServerAddress() {
        return nameServer;
    }

    @Override
    protected String getInstanceName() {
        return MQConstant.IC_LIGHT_CONTROL_MQ_INSTANCE_NAME;
    }

    @Override
    protected MqTopic[] getMqTopics() {
        MqTopic[] mqTopics = new MqTopic[1];
        mqTopics[0] = new MqTopic(
                MQConstant.IC_LIGHT_CONTROL_TOPIC, MQConstant.IC_LIGHT_CONTROL_TAG);
        return mqTopics;
    }
}
